<template>
	<div>
		<el-dialog title="添加轮播图" :visible.sync="addVisible" width="30%" :before-close="closeAddRotation">
			<el-form :model="rotationList" ref="addRotation" label-width="100px">
        <el-form-item label="图片名称" prop="bannerName" :rules="[
              { required: true, message: '请输入图片名称', trigger: 'blur' },
            ]">
        	<el-input type="text" v-model="rotationList.bannerName" placeholder="请输入图片名称"></el-input>
        </el-form-item>

				<el-form-item label="添加图片" prop="bannerImg" :rules="[
              { required: true, message: '请插入图片', trigger: 'blur' },
            ]">
          <el-input v-show="false" v-model="rotationList.bannerImg"/>
          <el-upload
            class="upload-demo"
            ref="upload"
            list-type="picture"
            action=""
            :limit="1"
            :on-change="imgVaildata"
            :auto-upload="false"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-upload="beforeUploadHandle"
            :http-request="handleUploadForm"
            >
            <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
          <!-- <input type="file" name="photo"><br> -->
        </el-form-item>

        <el-form-item label="显示状态" prop="status" :rules="[
              { required: true, message: '请选择是否启用', trigger: 'blur' },
            ]">
          <el-switch
            v-model="rotationList.onstatus" @change="onstatus(rotationList.onstatus)"
            active-text="启用" inactive-text="禁用">
          </el-switch>
        </el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="closeAddRotation">取 消</el-button>
				<el-button type="primary" @click="submitUpload('addRotation')">确 定</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
	export default {
		name: "",
		props: ["addVisible"],
		data() {
			return {
				rotationList: {
					bannerName: "",
          bannerImg:"",
          //以下两个变量用于判断用户状态
          status:0,
          onstatus:false,
				},
			}
		},
		methods: {
      //设置关闭添加页面方法
      closeAddRotation() {
          this.clearData()
      		this.$parent.addVisible = false
      },
      //清空图片方法
      clearFiles () {
          this.$refs['upload'].clearFiles();
      },
      //清除文本框数据，返回相对应文本框的值
      clearData(){
          this.rotationList={
            bannerName: "",
            bannerImg:"",
            //以下两个变量用于判断用户状态
            status:0,
            onstatus:false,
          }
          this.clearFiles()
      },
      //验证图片是否为空
      imgVaildata(file, fileList){
          var self = this
          console.log('vue 图片上传钩子函数')
          self.rotationList.bannerImg=file.name
          console.log(self.rotationList.bannerImg)
          if(file.name==null || file.name==""){
            self.rotationList.bannerImg=null
          }
      },
       //判断显示状态
       onstatus(onstatus){
         console.log(onstatus)
         if(onstatus===true){
           this.rotationList.status=1
         }else if(onstatus===false){
           this.rotationList.status=0
         }
       },
      /* */
      //判断表单数据是否为空
      //并提交数据
     submitUpload(params) {
       console.log("触发判断事件")
       var self = this
       this.$refs[params].validate((valid) => {
      	if (valid) {
          // if(params.file){
            self.$refs.upload.submit();
          // }else{
          //   self.handleUploadForm()
          // }
      	} else {
      		console.log('error submit!!');
      		return false;
      	}
      });
     },
     //触发删除事件
     handleRemove(file, fileList) {
       console.log("触发删除事件")
       if(file){
         this.rotationList.bannerImg=""
       }
       console.log(file, fileList);
     },
     handlePreview(file) {
       console.log("kukukuku")
       console.log(file);
     },
     /* */
      //上传文件前执行的方法,判断文件格式
      beforeUploadHandle(file) {
        console.log("执行上传前方法")
        if (
            file.type !== "image/png" &&
            file.type !== "image/jpeg"
        ) {
          this.$message.error("只支持.jpg、.jpeg、.jpe、.png文件！");
          return false;
        }
      },


      //执行添加方法
      handleUploadForm(param) {
        console.log(param)
        console.log(JSON.stringify(this.rotationList))
        let self = this
        //获取登录者信息
        var onlineManager = JSON.parse(sessionStorage.getItem("manager"))
        //获取当前页
        var page = sessionStorage.getItem("page")


        // 检测输入的数据中是否存在空格
        var bannerName = this.rotationList.bannerName
        if(bannerName.split(" ").length==1){
          //使用formData向后台发送数据
          let formData = new FormData()
          //在formData中加入我们需要的参数
          formData.append('file', param.file)
          //转换数据格式并向后台发送数据
          formData.append('banner', JSON.stringify(this.rotationList))
          console.log("开始向后端发送请求")




          // 向后端发送数据
          self.$http.post('/api/CakeShop/Banner/addImg', formData).then((res) => {
            console.log(res)
            //判断添加数据是否成功
            if (res.data.addSuccNum>0) {
              self.$message({
                message: res.data.msg,
                type: 'success',
                onClose: function() {
                  //添加完毕后清除文本框中内容
                  self.clearData()
                  //关闭修改界面
                  self.closeAddRotation()
                  //添加完数据返回首页
                  self.$parent.getRotationList(page)
                }
              });
            }else{
              self.$message({
                duration: 1500,
                message: res.data.msg,
                type: "error",
                onClose: function() {
                  self.loading = false;
                },
              });
            }
          })
        }else{
          self.$message({
            duration: 1500,
            message: "用户名中存在非法字符空格!",
            type: "error",
            onClose: function() {
              self.loading = false;
            },
          });
        }
      },
		}
	}
</script>
<style>
</style>
